package com.commons.validator.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * ExceptionControllerAdvice
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2021-01-08 15:36
 */
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(Exception.class)
    public String globalExceptionHandler(Exception e) {
        log.error("", e);
        return e.getMessage();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("", e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        errors.forEach(error ->{
            log.error(error.toString());
        });
        return e.getMessage();
    }
}
